import requests
import re

#1.先发起get 获取csrfmiddlewaretoken  和cookie
# login_url = 'http://127.0.0.1:8000/admin/login/?next=/admin/'
# response_login=requests.get(login_url)
# print(response_login.cookies)
#
# csrfmiddlewaretoken=re.search(r'<input type="hidden" name="csrfmiddlewaretoken" value="(.*?)">',response_login.text).group(1)
# print(csrfmiddlewaretoken)
#
# # 2.发起post 携带隐藏域 用户名 密码
# response_login = requests.post(login_url, data={
#     'csrfmiddlewaretoken': csrfmiddlewaretoken,
#     'username': 'admin',
#     'password': '123456',
# },cookies=response_login.cookies)
#
# print(response_login.text)
#


# 使用会话session 可以不用传cookies 会话会自己带这个数据

login_url = 'http://127.0.0.1:8000/admin/login/?next=/admin/'
session = requests.Session()
print(session.cookies)
# 验证会话会自己带可以不用传cookies这个数据 和获取隐藏域
response = session.request('get', login_url)
print(session.cookies)
# 获取隐藏域
csrfmiddlewaretoken=re.search(r'<input type="hidden" name="csrfmiddlewaretoken" value="(.*?)">',response.text).group(1)
print(csrfmiddlewaretoken)

# 发起post请求
response = session.request('post', login_url,data={
    'username': 'admin',
    'password': '123456',
    'csrfmiddlewaretoken': csrfmiddlewaretoken,
})
print(response.text)